package com.demo.validator;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import com.demo.dto.ReturenJson;
import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

public class BaseValidator extends Validator {

	//校验手机号码正则表达式
    private static final String mobilePattern = "\\b(1[3,4,5,7,8,9]\\d{9})\\b";

    //错误key后缀
    protected static final String ERROR_PREFIX_KEY = "错误码";
//    protected static final String ERROR_KEY = ":errorkey";

    //方便错误消息key的命名
    public String msgKey(String msg) {
        return ERROR_PREFIX_KEY + ":" + msg;
//        return msg + ERROR_KEY;
    }

    /**
     * 获取Validator过程中第一个错误信息
     * 后端验证主要为了验证非空以及处理绕过前端验证的非法请求
     * jfinal的Validator会将错误利用setAttr进行设置
     *
     * @param c
     * @return 第一个错误信息
     */
    public static Map<String, String> getFirstErrMsg(Controller c) {
        String findErrorAttrName = "";
        Enumeration<String> attrNames = c.getAttrNames();
        //获取第一个错误属性key
        if (attrNames != null) {
            while (attrNames.hasMoreElements()) {
                String attrName = attrNames.nextElement();
                findErrorAttrName = attrName;
//                if (attrName.lastIndexOf(ERROR_KEY) > 0) {
//                	findErrorAttrName = attrName;
//                	break;
//                }
            }
        }
        //获取第一个验证错误详情
        Map<String, String> map = new HashMap<String, String>();
        String errMsg = c.getAttr(findErrorAttrName);
        map.put("errCode", findErrorAttrName);
        map.put("errMsg", errMsg);
        return map;
    }

    /**
     * 验证是否合法手机号或邮箱
     * 一般用于验证用户名
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateMobileAndEmail(String field, String errorKey, String errorMsg) {
        validateRegex(field, mobilePattern, false, errorKey, errorMsg);
        validateEmail(field, errorKey, errorMsg);
    }

    /**
     * 验证是否合法手机号
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateMobile(String field, String errorKey, String errorMsg) {
        validateRegex(field, mobilePattern, false, errorKey, errorMsg);
    }

    @Override
    protected void validate(Controller c) {
        //启用快速失败
        setShortCircuit(true);
        //这里无需进行实现
    }

    @Override
    protected void handleError(Controller c) {
        //获取第一个验证错误详情
        Map<String, String> map  = getFirstErrMsg(c);
        c.renderJson(new ReturenJson(map.get("errCode"), map.get("errMsg")));
//        c.renderJson("{'errcmsg':'" + firstErrMsg + "'}");
    }

}
